package com.niit.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * JDBC工具类
 * 
 * @author Administrator
 *
 */
public class JDBCUtil {

	private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
	private static final String URL = "jdbc:mysql://localhost:3306/niit-jdbc?serverTimezone=Asia/Shanghai&useSSL=false&characterEncoding=utf8";
	private static final String USER = "root";
	private static final String PWD = "root";
	static {
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 *
	 * @return
	 */
	public static Connection getConnection() {
		try {
			return DriverManager.getConnection(URL, USER, PWD);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("Failed to get database connection.");
		}
	}

	/**
	 * 
	 * 
	 * @param conn
	 * @param st
	 */
	public static void closeDB(Connection conn, Statement st) {

		if (st != null) {
			try {
				st.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * 
	 * 
	 * @param conn
	 * @param st
	 * @param rs
	 * @throws SQLException
	 */
	public static void closeDB(Connection conn, Statement st, ResultSet rs) throws SQLException {
		if (rs != null) {
			rs.close();
		}
		if (st != null) {
			st.close();
		}
		if (conn != null) {
			conn.close();
		}
	}

}
